源代码
// 定义链表节点类
class ListNode {
constructor(value) {
this.value = value; // 节点存储的值
this.next = null; // 指向下一个节点的指针
}
}
// 创建包含100个随机整数节点的链表
function createRandomLinkedList(size) {
let head = null;
let current = null;
for (let i = 0; i < size; i++) {
const newNode = new ListNode(Math.floor(Math.random() * 100)); // 创建新节点,存放0到99之间的随机整数
if (head === null) {
head = newNode; // 如果链表为空,则新节点为头节点
current = head;
} else {
current.next = newNode; // 否则,将新节点添加到链表的末尾
current = newNode;
}
}
return head;
}
// 遍历链表并输出每个节点的值
function printLinkedList(head) {
let current = head;
while (current !== null) {
console.log(current.value); // 输出当前节点的值
current = current.next; // 移动到下一个节点
}
}
// 创建链表并输出每个节点的值
const head = createRandomLinkedList(100);
console.log("链表中的随机整数:");
printLinkedList(head);
运行结果
> 等待执行...
代码解释
链表节点定义
定义了链表节点类ListNode,每个节点包含一个整数值和指向下一个节点的指针。
创建随机链表
通过循环创建包含100个随机整数(0-99)的链表,每个新节点添加到链表尾部。
遍历链表
实现了链表遍历函数,从链表头开始,依次访问每个节点并输出其值。